package game.games.map2d;

import game.GameListener;
import game.GraphicUtil;
import game.Position;
import game.cellmap.AbstractCellMapGame;
import game.cellmap.CellMap;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;

public class Map2D extends AbstractCellMapGame<CellMap>
{
    private static Map2D instance;
    
    public synchronized static Map2D getInstance()
    {
        if (instance == null)
        {
            synchronized (Map2D.class)
            {
                instance = new Map2D();
            }
        }
        return instance;
    }
    
    public Map2D()
    {
        super(true, new CellMap(true, 50));
        final GameListener gameListener = GameListener.getInstance();
        gameListener.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e)
            {
                if (isRunning())
                {
                    getMap().getKeyAdapter().keyPressed(e);
                }
            }
        });
    }
    
    @Override
    public BufferedImage getImage()
    {
        Position imgSize = new Position(getMap().getCellSize() * getMap().getMapSize().getWidth(), getMap().getCellSize() * getMap().getMapSize().getHeight());
        BufferedImage img = new BufferedImage(imgSize.getWidth(), imgSize.getHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = img.createGraphics();
        GraphicUtil.fillRect(g, 0, 0, imgSize.getWidth(), imgSize.getHeight(), Color.WHITE);
        if (isRunning())
        {
            for (int index = 0; index < getMap().getMapSize().getSum(); index++)
            {
                Position position = getMap().calculatePosition(index);
                if (index == getMouseOverIndex())
                {
                    getMap().fillRect(g, position.getX(), position.getY(), Color.RED);
                }
                else
                {
                    getMap().drawRect(g, position.getX(), position.getY(), Color.BLACK);
                }
                getMap().drawString(g, String.valueOf(index), ((getMap().getCellSize() / 10) * 6), position.getX(), position.getY(), Color.BLUE);
            }
            g.drawImage(img, 0, 0, null);
        }
        setPreferredSize(imgSize.getWidth(), imgSize.getHeight());
        return img; 
    }
    
    @Override
    protected void doNext()
    {
    }
    
    @Override
    protected synchronized void reset()
    {
        Position newSize = new Position(100, 10);
        if (newSize.equals(getMap().getMapSize()) == false)
        {
            getMap().setMapSize(newSize);
        }
        super.reset();
    }
    
    public static void main(String[] args)
    {
        Thread t = new Thread(Map2D.getInstance(), "Map2D");
        t.start();
    }
}
